<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: ../unilogin/index.html");
    exit();
}

include 'db_connect.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $post_id = $_POST["id"];
    $title = $_POST["title"];
    $content = $_POST["content"];
    
    // 获取帖子原作者信息
    $sql = "SELECT author FROM posts WHERE id = $post_id";
    $result = $conn->query($sql);
    $post = $result->fetch_assoc();
    
    // 验证权限
    if ($_SESSION['username'] != $post["author"]) {
        die("您没有权限修改这篇文章！");
    }

    $title = $conn->real_escape_string($title);
    $content = $conn->real_escape_string($content);

    $sql = "UPDATE posts SET title='$title', content='$content', updated_at=CURRENT_TIMESTAMP WHERE id=$post_id";

    if ($conn->query($sql) === TRUE) {
        header("Location: post.php?id=$post_id&updated=1");
    } else {
        echo "修改失败: " . $conn->error;
    }
    $conn->close();
} else {
    header("Location: index.php");
}
?>
